package scms.service.stock;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

import lac.framework.common.message.Result;
import lac.framework.core.model.ModelLogicBean;
import lac.framework.security.session.AccountUtil;
import lac.model.core.persistent.Session;
import lac.model.core.persistent.SessionFactory;
import lac.model.core.persistent.criterion.Criteria;
import lac.model.core.persistent.criterion.Restrictions;
import lac.serviceuint.tool.ApplicationContextBean;

@Service
public class UpdateStockLogicBean extends ModelLogicBean<Map<String, Object>> {

	@Value("${sleepms:10}")
	private Long sleepms;
	@Autowired(required=false)
	private ApplicationContextBean applicationContextBean;

	public void doLogic() throws Exception {
		System.out.println(AccountUtil.getToken());
		Session session = getCurrentSession();
		Map<String, Object> data = getModelData();
		UpdateStockLogicBean logicBean = applicationContextBean.getApplicationContext().getBean(UpdateStockLogicBean.class);
		logicBean.update(session,getModelName(),data);
		
	}
	
	@HystrixCommand(/*fallbackMethod = "getFallback",*/ commandKey="updateStock",commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000") })
	public void update(Session session,String modelName,Map<String, Object> data ){
		try {
			Thread.sleep(sleepms);
		} catch (InterruptedException e) {
			throw new RuntimeException("stock time out !");
		}
		
		Criteria criteria = new Criteria();
		criteria.add(Restrictions.eq("productName", data.get("productName")));
		List<Map<String, Object>> list = session.query(modelName,criteria);
		if (list.size() == 0) {
			session.save(modelName, data);
		} else {
			Map<String, Object> stock = list.get(0);
			Integer amount = (Integer) stock.get("amount") + Integer.parseInt(data.get("amount").toString());
			stock.put("amount", amount);
			session.update(modelName, stock);
		}
	}
	
	 /* void getFallback() {
		 throw new RuntimeException();
	 }*/

	public Long getSleepms() {
		return sleepms;
	}

	public void setSleepms(Long sleepms) {
		this.sleepms = sleepms;
	}

	
	
}
